package com.itboye.textileexpres.myset;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.textileexpes.beans.CountrySortModel;
import com.itboye.textileexpes.beans.UserBean;
import com.itboye.textileexpes.presenter.MainPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseActivity;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.util.CameraPopupWindow;
import com.itboye.textileexpres.util.CharacterParserUtil;
import com.itboye.textileexpres.util.GetCountryNameSort;
import com.itboye.textileexpres.util.ImageCompress;
import com.itboye.textileexpres.util.IsMobileNumPhone;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.util.UploadImage;
import com.itboye.textileexpres.util.UploadImage.OnUploadlistener;
import com.itboye.textileexpres.util.XImageLoader;
import com.itboye.textileexpres.widget.RoundImageView;
import com.itboye.textileexpres.widget.SexPopupWindow;
import com.itboye.textileexptes.config.GlobalConfig;
/**
 * 我的资料
 */
public class ActivityPersonDate extends BaseActivity implements
		OnClickListener, OnUploadlistener, Observer {
	TextView title;
	ImageView back, img_other;
	RelativeLayout user_image_layout, userName_layout, account_layout,
			change_sex_layout, sign_layout, QR_code_layout, area_layout,
			Receipt_address_layout, mobil_layout, mailbox_layout, WX_layout,
			company_layout, posion_layout;
	RoundImageView usericon_im;
	ImageView QR_code_img;
	TextView userName_txt, sign_txt;
	TextView account_txt, sex_txt, area_txt, Receipt_address_txt, mobil_txt,
			mailbox_txt, WX_txt, company_txt, posion_txt;
	private CameraPopupWindow mCameraPopupWindow;
	private SexPopupWindow sexPopupWindow;
	private GetCountryNameSort countryChangeUtil;
	private CharacterParserUtil characterParserUtil;
	private List<CountrySortModel> mAllCountryList;
	String beforText = null;
	private String localSelectPath;
	// area_txt/
	private static final int BEGIN_CODE = 0;
	private static final int END_CODE = 1;
	String countryname;
	private String cityId;
	TextView area_txtcity;
	String uid;
	MainPresenter mainPresenter;
	private String IMGE_HEAD;
	String sex;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_person_date;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		title.setText(R.string.personal_data);
		img_other.setVisibility(View.GONE);
		uid = (String) SPUtils.get(this, null, SpPublicParams.UID, "");
		mAllCountryList = new ArrayList<CountrySortModel>();
		countryChangeUtil = new GetCountryNameSort();
		characterParserUtil = new CharacterParserUtil();
		initCountryList();

		countryname = (String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.COUNTRYNMAW, "");
		cityId = (String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.COIN, "");
		area_txt.setText(countryname);
		IntentFilter intentFilterAvart2 = new IntentFilter("City");
		this.registerReceiver(avartBroadcastReceiver, intentFilterAvart2);
		mainPresenter = new MainPresenter(this);
		IntentFilter filter = new IntentFilter("updatechange");
		registerReceiver(receiver, filter);
		initdate();

	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			initdate();
		}

	};
	
	private void initdate() {
		// TODO Auto-generated method stub
		XImageLoader.load(
				(String) SPUtils.get(this, null, SpPublicParams.URL, ""),
				usericon_im);
		countryname = (String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.COUNTRYNMAW, "");
		cityId = (String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.COIN, "");
		area_txt.setText(countryname);
		userName_txt.setText((String) SPUtils.get(ActivityPersonDate.this,
				null, SpPublicParams.NICK_NAME, ""));
		sign_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.SIGNATURE, ""));
		mailbox_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.Email, ""));
		company_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.Company, ""));
		posion_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.Job, ""));
		mobil_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.PHONE_MODEL, ""));
		Receipt_address_txt.setText((String) SPUtils
				.get(ActivityPersonDate.this, null,
						SpPublicParams.AcceptAddress, ""));

		String sex = (String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.SEX, "");

		if ("1".equals(sex)) {
			sex_txt.setText(R.string.h1118);
		} else {
			sex_txt.setText(R.string.h1119);
		}
		Receipt_address_txt.setText((String) SPUtils
				.get(ActivityPersonDate.this, null,
						SpPublicParams.AcceptAddress, ""));
		account_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.PHONE_MODEL, ""));
		String resultData = (String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.URL, "");
		WX_txt.setText((String) SPUtils.get(ActivityPersonDate.this, null,
				SpPublicParams.WX, ""));
		if ("".equals(resultData) || resultData == "") {
			usericon_im.setImageResource(R.drawable.person_img);
		} else {
			XImageLoader.load(resultData, usericon_im);
		}

	}

	BroadcastReceiver avartBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			countryname = (String) SPUtils.get(ActivityPersonDate.this, null,
					SpPublicParams.COUNTRYNMAW, "");

			area_txt.setText(countryname);
		};
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		/***
		 * 头锟斤拷
		 */
		case R.id.user_image_layout:
			mCameraPopupWindow = new CameraPopupWindow(ActivityPersonDate.this,
					onclicklister);
			mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.userName_layout:
			intent = new Intent(ActivityPersonDate.this, ActivityNickName.class);
			startActivity(intent);
			break;
		case R.id.userName_txt:
			intent = new Intent(ActivityPersonDate.this, ActivityNickName.class);
			startActivity(intent);
			break;
		case R.id.change_sex_layout:
			sexPopupWindow = new SexPopupWindow(ActivityPersonDate.this,
					sexclick);
			sexPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.sign_layout:
			intent = new Intent(ActivityPersonDate.this,
					ActivityPersonSign.class);
			startActivity(intent);
			break;
		case R.id.WX_txt:
			intent = new Intent(ActivityPersonDate.this, ActivityWeChat.class);
			startActivity(intent);
			break;
		case R.id.area_layout:
			intent = new Intent();
			intent.setClass(ActivityPersonDate.this, CishiCityActivity.class);
			intent.putExtra("strCh", countryname);
			startActivityForResult(intent, 12);
			break;
		case R.id.Receipt_address_layout:
			intent = new Intent(ActivityPersonDate.this,
					ActivityAddressManage.class);
			startActivity(intent);
			break;
		case R.id.mobil_layout:
			break;
		case R.id.mailbox_layout:
			intent = new Intent(ActivityPersonDate.this,
					ActivityPersonEmail.class);
			startActivity(intent);
			break;
		case R.id.mailbox_txt:
			intent = new Intent(ActivityPersonDate.this,
					ActivityPersonEmail.class);
			startActivity(intent);
			break;
		case R.id.company_layout:
			intent = new Intent(ActivityPersonDate.this,
					ActivityMyCompany.class);
			startActivity(intent);
			break;
		case R.id.company_txt:
			intent = new Intent(ActivityPersonDate.this,
					ActivityMyCompany.class);
			startActivity(intent);
			break;
		case R.id.posion_layout:
			intent = new Intent(ActivityPersonDate.this, ActivityMyOffer.class);
			startActivity(intent);
			break;
		case R.id.posion_txt:
			intent = new Intent(ActivityPersonDate.this, ActivityMyOffer.class);
			startActivity(intent);
			break;
		case R.id.sign_txt:
			intent = new Intent(ActivityPersonDate.this,
					ActivityPersonSign.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = super.handlerError(data);
		if (entity != null) {
			if (entity.getEventType().equals(
					MainPresenter.UpdateUserInfoSuccessEvent)) {
				SPUtils.put(this, null, SpPublicParams.SEX, sex);
			} else if (entity.getEventType().equals(
					MainPresenter.UpdateUserInfoFailureEvent)) {
				toast("" + entity.getData());
			}
		}
	}

	private void initCountryList() {
		String[] countryList = getResources().getStringArray(
				R.array.country_code_list_ch);

		for (int i = 0, length = countryList.length; i < length; i++) {
			String[] country = countryList[i].split("\\*");

			String countryName = country[0];
			String countryNumber = country[1];
			String countrySortKey = characterParserUtil.getSelling(countryName);
			CountrySortModel countrySortModel = new CountrySortModel(
					countryName, countryNumber, countrySortKey);
			String sortLetter = countryChangeUtil
					.getSortLetterBySortKey(countrySortKey);
			if (sortLetter == null) {
				sortLetter = countryChangeUtil
						.getSortLetterBySortKey(countryName);
			}

			countrySortModel.sortLetters = sortLetter;
			mAllCountryList.add(countrySortModel);
		}

	}

	OnClickListener sexclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.men: {
				UserBean bean = new UserBean();
				bean.setUid(IsMobileNumPhone.isUid());
				sex = "1";
				bean.setSex(sex);
				mainPresenter.updateUserInfoByUid(bean);
			}
				break;
			case R.id.women: {
				UserBean bean = new UserBean();
				bean.setUid(IsMobileNumPhone.isUid());
				sex = "0";
				bean.setSex(sex);
				mainPresenter.updateUserInfoByUid(bean);
			}
				break;
			default:
				break;
			}
		}
	};

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					toast("请确认已经插入SD卡");
				}
				break;
			case R.id.pick_image:
				Intent intent2 = new Intent();
				intent2.setType("image/*");// 可选择图片视频
				// 修改为以下两句代码

				intent2.setAction(Intent.ACTION_PICK);
				intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
				// intent.setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				// "image/*");
				startActivityForResult(intent2, 0);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};

	private String picture_name;

	private String fileName;
	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	public static final int IMAGE_COMPLETE = 6; // // 结果

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage = data.getData();
				localSelectPath = null;
				localSelectPath = getRealPathFromURI(selectedImage);
				localSelectPath = ImageCompress.compress(localSelectPath);
				Intent intent2 = new Intent(this, ClipActivity.class);
				intent2.putExtra("path", localSelectPath);
				startActivityForResult(intent2, IMAGE_COMPLETE);
			} else if (requestCode == 3) {
				// Toast.makeText(App.ctx, "haha", 0).show();
				// emailtext.setText("" + data.getStringExtra("email"));
			} else if (requestCode == 1) {
				// nicktext.setText("" + data.getStringExtra("nickname"));
			} else if (requestCode == 6) {
				UploadImage.getInstance().execute(localSelectPath, this);
				mCameraPopupWindow.dismiss();
			} else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
					&& resultCode == RESULT_OK) {
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // / 检测sd是否可用
					Log.i("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				picture_name = android.text.format.DateFormat.format(
						"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				// SavePicInLocal(bitmap);
				FileOutputStream b = null;
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;

				try {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				// fileName=ImageCompress.compress(fileName);
				UploadImage.getInstance().execute(fileName, this);
				mCameraPopupWindow.dismiss();

			} else if (requestCode == 12) {
				if (resultCode == RESULT_OK) {
					Bundle bundle = data.getExtras();
					String countryName = bundle.getString("countryName");
					String countryNumber = bundle.getString("countryNumber");

					// editText_countryNum.setText(countryNumber);
					area_txt.setText(countryName);

				}
			} else if (requestCode == 12) {
				Bundle bundle = data.getExtras();
				String provice = bundle.getString("provice");
				String cityName = bundle.getString("countryName");
				area_txtcity.setText(provice + "\t" + cityName);
			}

		}
	}

	/**
	 * 该方法用于获取文件的真实路径从URI 从相机拍摄
	 */
	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	/**
	 * 该调用系统的图片截取方法已被遗弃，华为手机报错
	 * @param url
	 */
	public void startCrop(Uri url) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(url, "image/*");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		// intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);

	}

	@Override
	public void OnSuccess(String resultData) {
		// TODO Auto-generated method stub
		toast("上传成功");
		String time = String.valueOf((int) (Math.random() * 10));
		SPUtils.put(this, null, SpPublicParams.URL, GlobalConfig.IMAGE_HEAD
				+ uid + "&random=" + time);
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + resultData);
		XImageLoader.load(
				(String) SPUtils.get(this, null, SpPublicParams.URL, ""),
				usericon_im);
		System.out.println(">>>>>>>>>>>>OOO\n"
				+ (String) SPUtils.get(this, null, SpPublicParams.URL, ""));

		// 发送广播更新头像
		Intent intent2 = new Intent("newshead");
		sendBroadcast(intent2);
	}

	@Override
	public void OnError(String resultData) {
		// TODO Auto-generated method stub
		toast("上传失败");
	}

}
